package com.jin.test.impl;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.jin.test.service.MergepdfTestService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * @Package:com.jin.test.impl
 * @ClassName: MergepdfTestImpl
 * @Description:
 * @Date: 2024/07/26 23:47
 * @Author: Jin
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MergepdfTestImpl implements MergepdfTestService {

    /**
     * pdf合并方法
     * @param bytes
     * @return
     */
    @Override
    public byte[] mergepdf(List<byte[]> bytes) {
        byte[] pdfs = new byte[0];
        try{
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Document document = new Document();
            PdfCopy copy = new PdfCopy(document, bos);
            document.open();
            for (byte[] bs : bytes) {
                PdfReader reader = new PdfReader(bs);
                int pageTotal = reader.getNumberOfPages();
                log.info("pdf的页码数是 ==>{}", pageTotal);
                for (int pageNo = 1; pageNo <= pageTotal; pageNo++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, pageNo);
                    copy.addPage(page);
                }
                reader.close();
            }
            document.close();
            pdfs = bos.toByteArray();
            bos.close();
            copy.close();
        } catch (Exception e){
            log.error("pdf合并失败！");
        }
        return pdfs;
    }
}
